package org.example;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    /**
     * 当请求到达后，先提取出用户名和密码，然后调用 req.login 方法进行登录，如果登录失败，则跳转到登录页面。
     * 登录完成后，通过获取登录用户信息以及判断登录用户角色，来确保用户是否登录成功。
     * 如果登录成功，就跳转到用户角色对应的项目应用首页，否则就跳转到登录页面。
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        try {
            req.login(username, password);
        } catch (ServletException e) {
            resp.sendRedirect("/login.jsp");
            return;
        }
        boolean login = req.getUserPrincipal() != null && req.isUserInRole("admin");
        if (login) {
            resp.sendRedirect("/admin/hello");
        } else {
            resp.sendRedirect("/user/hello");
        }
    }
}
